package org.jground.rx.ui.zk.viewControl;

import java.util.List;

import org.jground.rx.IRXObject;
import org.jground.rx.IRXVersionValue;
import org.jground.rx.RXAttribute;
import org.jground.rx.RXDataState;
import org.jground.rx.ui.IUIAttribute;
import org.jground.rx.ui.zk.UIFrame;
import org.jground.util.DateUtils;
import org.jground.zk.zulX.VboxX;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Toolbarbutton;

public class UIHistoryNavigation extends VboxX implements EventListener {

    private static String TIMEINDEX = "_timeindex";

    private IRXObject moDataObject;
    private RXAttribute moAttribute;
    private List<IRXVersionValue> hv;
    //
    private Toolbarbutton toggleLink;
    private String onText = "historical values";
    private String offText = "close historical";
    private boolean toggleOn = false;
    private IUIAttribute<Component,UIFrame> ui;

    public UIHistoryNavigation(UIFrame uiFrame, RXAttribute moAttribute, IUIAttribute<Component,UIFrame> ui) {
        this.moAttribute = moAttribute;
        this.ui = ui;
    }

    public void updateActionLinks() {
        this.removeAll();
        if (!moAttribute.isHistory()) {
            return;
        }
        this.add(toggleLink = new Toolbarbutton(toggleOn ? offText : onText));
        toggleLink.addEventListener(Events.ON_CLICK, this);
        if (toggleOn) {
            for (int index = 0; index < hv.size(); index++) {
                IRXVersionValue v = hv.get(index);
                String label = RXDataState.getByInt(v.getState()).toString().charAt(0) + " ";
                label += DateUtils.formatToDateTime(v.getTime());
                label += " ("+v.getUserName()+")";
                Toolbarbutton historyButton = new Toolbarbutton(label);
                historyButton.setAttribute(TIMEINDEX, index);
                historyButton.addEventListener(Events.ON_CLICK, this);
                this.add(historyButton);
            }
        }
    }

    public void setMoDataObject(IRXObject moDataObject) {
        this.moDataObject = moDataObject;
        hv = moDataObject.getVersionValues(moAttribute.getName());
        updateActionLinks();
    }

    public void onEvent(Event event) throws Exception {
        hv = moDataObject.getVersionValues(moAttribute.getName());
        if (event.getTarget() == toggleLink) {
            toggleOn = !toggleOn;
        } else if (event.getTarget() instanceof Toolbarbutton) {
            Toolbarbutton actionLink = (Toolbarbutton) event.getTarget();
            int index = (Integer) actionLink.getAttribute(TIMEINDEX);
            ui.set(hv.get(index).getStringValues());
        }
        updateActionLinks();
    }

}